package com.loongtech.bi.action.realTime;

import com.loongtech.bi.entity.system.EntityBiServer;
import com.loongtech.bi.manager.realTime.BossRealTimeManager;
import com.loongtech.bi.manager.realTime.BossRealTimeManager.BossRealTimeDetailData;
import com.loongtech.bi.manager.realTime.ServerRealTimeManager;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.ConfigManager;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.support.AsyncHttpClientUtils;
import com.loongtech.bi.support.Session;
import com.loongtech.bi.support.chart.ChartTool;
import com.loongtech.bi.support.chart.ChartType;
import com.loongtech.bi.support.chart.ChartUIData;
import com.loongtech.core.util.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * 实时数据-汇总Action
 * @author Marin
 * @date 2015年09月17日
 */
@Controller
@Scope("view")
public class BossRealTimeAction {
	private List<BossRealTimeManager.BossRealTimeData> datas;  // 前端要显示的实时汇总数据
	private List<BossRealTimeManager.BossRealTimeDetailData> allDetailDatas;  // 所有详细数据
	private List<BossRealTimeManager.BossRealTimeDetailData> detailDatas;  // 前端要显示的详细数据
	private ChartUIData chartData;  // 前端要显示的曲线图数据
    private List<ServerRealTimeManager.OnlineRealTimeData> onlineRealTimeDatas; // 项目整体实时在线数据
    private ChartUIData onlineRealTimeChart;  // 前端要显示的整体实时在线曲线图数据

	private String selectedItem = "all";  // all=全部平台;ioszb=ios正版;hf=混服;yyb=应用宝;yhlm=硬核联盟

	//private static AtomicInteger lastDatasHashCode = new AtomicInteger(0);  // 最近一次datas对象的hashCode
	private String lastUpdateTimeStr = "";  // 前端要访问的最近更新时间字符串
	private String lastMaxOnlineNumStr = "";  // 前端要访问的当前最高负载：xx渠道xxx服xxxx人
	private String serverNumStr = "";  // 共xx组服务器

	private String activateData = "";  // 前端要访问的激活设备数

    private static long lastQueryTime = 0L;  // 最后一次访问本页面的时间（2分钟内只能访问一次）

	@Autowired
	private SysLogManager sysLogManager;
    @Autowired
    ConfigManager configManager;
	@Autowired
	private Session session;
	@Autowired
	private BossRealTimeManager bossRealTimeManager;
    @Autowired
    ServerRealTimeManager serverRealTimeManager;
	
	@PostConstruct
	public void init() {
		search();
	}
	public void search() {
		sysLogManager.addLog(session.getUserName(), "实时数据-实时监控");

        if ((Time.currentTime() - lastQueryTime)  < 2 * Time.MIN) {
            System.out.println("查询太频繁，不查数据库了，直接返回老数据");
            return;
        } else {
            System.out.println("查数据库");
            lastQueryTime = Time.currentTime();
        }

        long lastupdatetime = bossRealTimeManager.getMaxUpdateTime();
        lastUpdateTimeStr = "最近一次更新时间为：" + Time.getCeil1(lastupdatetime);

        Date d = Time.currentDate();

        onlineRealTimeDatas = new ArrayList<>(); // 项目整体实时在线数据
        onlineRealTimeChart = null; // 项目整体实时在线图表
        onlineRealTimeDatas = serverRealTimeManager.getOnlineRealTimeDatas(d);
        if (onlineRealTimeDatas != null && onlineRealTimeDatas.size() > 0) {
            onlineRealTimeChart = new ChartUIData();
            onlineRealTimeChart.setJsonStr(new ChartTool(onlineRealTimeDatas, ServerRealTimeManager.OnlineRealTimeData.class, onlineRealTimeChart.getSelectItem()).loadData(onlineRealTimeChart.getJsonType()));
        } else {
            onlineRealTimeChart = null;
        }

        datas = bossRealTimeManager.getBossRealTimeData(d);  // 汇总数据
		allDetailDatas = bossRealTimeManager.getBossRealTimeDetailData(d);  // 详细数据

        String url = configManager.getConfigValueByName(ConfigManager.ALL_ACTIVATE_URL);
        if (url != null) {
            AsyncHttpClientUtils.asyncSendAllActiveDataRequest(this, url + Time.getDateStr(Time.currentDate()));
        } else {
            System.out.println("需要配置ALL_ACTIVATE_URL");
        }
        BossRealTimeManager.BossRealTimeData activate = bossRealTimeManager.new BossRealTimeData();
        activate.setTitle("激活设备");
        datas.add(0, activate);
        activate.setValue(activateData);

        selectItem();
	}

	public void selectItem() {
        if (allDetailDatas == null || allDetailDatas.size() <= 0) {
            detailDatas = null;
            chartData = null;
            lastMaxOnlineNumStr = "当前全服最高负载为0";
            serverNumStr = BossRealTimeManager.INDEX2NAME.get(selectedItem) + "共0组服务器";  // 服务器数量
            return;
        }

        Collections.sort(allDetailDatas, bossRealTimeManager.new BossRealTimeDetailData().comparatorOnlineReverse);
        BossRealTimeManager.BossRealTimeDetailData maxData = allDetailDatas.get(allDetailDatas.size() - 1);
        lastMaxOnlineNumStr = "当前全服最高负载：" + maxData.getItemName() + "渠道" + maxData.getServername() + "服" + maxData.getOnlinenum() + "人";

        if ("all".equals(selectedItem)) {
			detailDatas = allDetailDatas;
		} else {
			detailDatas = new ArrayList<>();
			for (BossRealTimeManager.BossRealTimeDetailData d : allDetailDatas) {
				if (selectedItem.equals(d.getItem())) {
					detailDatas.add(d);
				}
			}
		}

        // 过滤未开放的服
        Iterator<BossRealTimeDetailData> iter = detailDatas.iterator();
        while(iter.hasNext()){
            EntityBiServer s = BiPlatformManager.SERVER_MAP.get(((BossRealTimeManager.BossRealTimeDetailData) iter.next()).getServerid());
            if (s == null) {
                iter.remove();
            }
        }

        if (detailDatas != null && detailDatas.size() > 0) {
            serverNumStr = BossRealTimeManager.INDEX2NAME.get(selectedItem) + "共" + detailDatas.size() + "组服务器";  // 服务器数量

            chartData = new ChartUIData();
            chartData.setJsonType(ChartType.COLUMN.type);
            chartData.setJsonStr(new ChartTool(detailDatas.size() > 20 ? detailDatas.subList(detailDatas.size() - 20, detailDatas.size()) : detailDatas, BossRealTimeManager.BossRealTimeDetailData.class, chartData.getSelectItem()).loadData(chartData.getJsonType()));

            Collections.sort(detailDatas, bossRealTimeManager.new BossRealTimeDetailData().comparatorOnline);
        } else {
            serverNumStr = BossRealTimeManager.INDEX2NAME.get(selectedItem) + "共0组服务器";  // 服务器数量
            chartData = null;
        }
	}

	public List<BossRealTimeManager.BossRealTimeData> getDatas() {
		return datas;
	}

	public void setDatas(List<BossRealTimeManager.BossRealTimeData> datas) {
		this.datas = datas;
	}

	public List<BossRealTimeManager.BossRealTimeDetailData> getDetailDatas() {
		return detailDatas;
	}

	public void setDetailDatas(List<BossRealTimeManager.BossRealTimeDetailData> detailDatas) {
		this.detailDatas = detailDatas;
	}

	public ChartUIData getChartData() {
		return chartData;
	}

	public void setChartData(ChartUIData chartData) {
		this.chartData = chartData;
	}

	public String getLastUpdateTimeStr() {
		return lastUpdateTimeStr;
	}

	public void setLastUpdateTimeStr(String lastUpdateTimeStr) {
		this.lastUpdateTimeStr = lastUpdateTimeStr;
	}

	public List<BossRealTimeManager.BossRealTimeDetailData> getAllDetailDatas() {
		return allDetailDatas;
	}

	public void setAllDetailDatas(List<BossRealTimeManager.BossRealTimeDetailData> allDetailDatas) {
		this.allDetailDatas = allDetailDatas;
	}

	public String getSelectedItem() {
		return selectedItem;
	}

	public void setSelectedItem(String selectedItem) {
		this.selectedItem = selectedItem;
	}

	public String getLastMaxOnlineNumStr() {
		return lastMaxOnlineNumStr;
	}

	public void setLastMaxOnlineNumStr(String lastMaxOnlineNumStr) {
		this.lastMaxOnlineNumStr = lastMaxOnlineNumStr;
	}

	public String getServerNumStr() {
		return serverNumStr;
	}

	public void setServerNumStr(String serverNumStr) {
		this.serverNumStr = serverNumStr;
	}

    public List<ServerRealTimeManager.OnlineRealTimeData> getOnlineRealTimeDatas() {
        return onlineRealTimeDatas;
    }

    public void setOnlineRealTimeDatas(List<ServerRealTimeManager.OnlineRealTimeData> onlineRealTimeDatas) {
        this.onlineRealTimeDatas = onlineRealTimeDatas;
    }

    public String getActivateData() {
		return activateData;
	}
	public void setActivateData(String activateData) {
		this.activateData = activateData;
	}
	public ChartUIData getOnlineRealTimeChart() {
        return onlineRealTimeChart;
    }

    public void setOnlineRealTimeChart(ChartUIData onlineRealTimeChart) {
        this.onlineRealTimeChart = onlineRealTimeChart;
    }
}
